<template>
    <div>
        <el-upload
                :before-upload="beforeAvatarUpload"
                :headers="{ authorization: token }"
                :on-success="handleAvatarSuccess"
                :show-file-list="false"
                action="http://localhost:8501/file/upload"
                class="avatar-uploader"
                name="file"
        >
            <!-- 根据接收到的 avatarUrl 显示图片或上传按钮 -->
            <img v-if="avatarUrl" :src="'http://localhost:8501' + avatarUrl" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</template>

<script>
import {getToken} from '@/utils/auth';

export default {
    name: 'Upload',
    props: {
        // 接收父组件传递的 v-model 值
        value: {
            type: String,
            required: true,
        },
    },
    data() {
        return {
            token: 'Bearer ' + getToken(),
            avatarUrl: this.value, // 初始化时使用父组件传递的值
        };
    },
    methods: {
        handleAvatarSuccess(res, file) {
            // 上传成功后更新 avatarUrl，并通过 $emit 将数据传递给父组件
            this.avatarUrl = res.data;
            this.$emit('input', res.data); // 触发父组件的 v-model 更新
        },
        beforeAvatarUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isLt2M;
        },
    },
};
</script>


<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
